package net.imagine.backend.mockrmi.util;

import java.net.InetSocketAddress;

import net.imagine.backend.mockrmi.remote.protocol.RequestBean;
import net.imagine.backend.mockrmi.remote.protocol.ResponseBean;
import net.imagine.backend.mockrmi.remote.server.RequestProcessor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 工具类，提供uri对应ip,端口号解析；id与实际注册id转换等
 */
public class MockRmiUtils {
	private static final Log logger = LogFactory.getLog(MockRmiUtils.class);
	public static final int PORT = 120000;

	/**
	 * 把uri转换成domain、port、id。
	 * 
	 * @param uri
	 *            uri格式：[protocol://]domain[:port]/id
	 * 
	 * @return String[]{domain,port,id}
	 */
	public static String[] parseUri(String uri) {
		String[] result = new String[3];

		int protocolEndIndex = uri.indexOf("://");
		int portSepIndex = uri.lastIndexOf(':');
		int ipStartIndex = protocolEndIndex < 0 ? 0 : protocolEndIndex + 3;
		int portStartIndex = (portSepIndex < 0 || portSepIndex == protocolEndIndex) ? -1 : portSepIndex + 1;
		int idStartIndex = 1 + uri.indexOf('/', portStartIndex < 0 ? ipStartIndex : portStartIndex);
		int ipEndIndex = portStartIndex < 0 ? idStartIndex - 1 : portStartIndex - 1;

		if (protocolEndIndex < 0) {
			logger.debug("no protocol. yes, you know we never mind it");
		}
		result[0] = uri.substring(ipStartIndex, ipEndIndex);
		if (portStartIndex < 0) {
			logger.debug("no port, use default port" + PORT);
			result[1] = "" + PORT;
		} else {
			result[1] = uri.substring(portStartIndex, idStartIndex - 1);
		}
		result[2] = uri.substring(idStartIndex);
		return result;
	}

	/**
	 * 打包输出结果，把结果对象和id封装成一个{@link ResponseBean}
	 * 
	 * @param id
	 *            请求的id
	 * @param ret
	 *            服务组件的返回的结果
	 * @return ResponseBean对象
	 */
	public static ResponseBean packResponse(String id, Object ret) {
		ResponseBean response = new ResponseBean();
		response.setId(id);
		response.setReturnValue(ret);
		return response;
	}

	/**
	 * 获取组件的实际id，更具服务器的端口号和注册在该端口的id，决定组件的实际id(${prort}:${id})
	 * 
	 * @param port
	 *            端口号
	 * @param id
	 *            id
	 * @return ${prort}:${id};
	 */
	public static String genId(int port, String id) {
		return port + ':' + id;
	}

	/**
	 * 服务器处理收到对象后的结果
	 * 
	 * @param message
	 *            服务器收到的对象
	 * @param localAddr
	 *            服务器本地地址（用于获取端口）
	 * 
	 * @return 服务器处理的结果
	 * @see RequestProcessor#processRequest(RequestBean, int)
	 */
	public static ResponseBean handlerMessage(Object message, InetSocketAddress localAddr) {
		ResponseBean response = null;
		if (message instanceof RequestBean) {
			RequestBean request = (RequestBean) message;
			response = RequestProcessor.processRequest(request, localAddr.getPort());
		} else {
			logger.warn("Bad Request! request is not instance of RequestBean");
			response = packResponse("", new ClassCastException("request is not instance of RequestBean"));
		}
		return response;
	}

	public static void main(String... args) {
		String[] re = MockRmiUtils.parseUri("http://sanans:8090/123123");
		System.out.println("ip:" + re[0] + ",port:" + re[1] + ",id:" + re[2]);
	}
}
